<template>
  <div class="apply">
    <van-nav-bar 
      :title="loanName + '申请'" 
      fixed 
      left-arrow 
      @click-left="onClickLeft" 
    />
    <van-panel title="基本信息">
      <van-cell-group>        
        <info-picker
          v-if="displayLoanProj"
          resultValue="loanProj"
          label="贷款项目"
          :value="loanProj != '' ? loanProj.name : ''"
          placeholder="选择贷款项目"
          :columns="loanList"
          @picker-confirm="loanProjConfirm"
          ref="loanProjPicker"
        >
        </info-picker>
        <van-field
          v-model.trim="applicant"
          required
          clearable
          autofocus
          label="申请人"
          placeholder="请输入"
        />
        <van-cell class="form" title="性别">
          <van-radio-group v-model="gender">
            <van-radio name="1">男</van-radio>
            <van-radio name="0">女</van-radio>
          </van-radio-group>
        </van-cell>
        <info-picker
          resultValue="certificateType"
          label="证件类型"
          :value="certificateType != '' ? certificateType.name : ''"
          placeholder="选择证件类型"
          :columns="certificateTypes"
          @picker-confirm="pickerConfirm"
        >
        </info-picker>
        <van-field
          v-model.trim="certificateNum"
          required
          clearable
          label="证件号码"
          placeholder="请输入"
        />
        <van-cell class="form" title="婚姻状况">
          <van-radio-group v-model="marriage">
            <van-radio name="0">未婚</van-radio>
            <van-radio name="1">已婚</van-radio>
            <van-radio name="2">离异</van-radio>
          </van-radio-group>
        </van-cell>
        <van-cell v-if="id != ''" class="form" title="申请额度">
          <van-slider 
            v-model="price" 
            bar-height="5px"
            :max="priceRange[1]"
            :min="priceRange[0]"
          >
            <div class="buttonWrap" slot="button">
              <div class="sliderText">
                {{ price }}万
              </div>
              <div class="button"></div>
            </div>
          </van-slider>
        </van-cell>
        <van-cell v-if="id != ''" class="form" title="贷款期限">
          <van-slider 
            v-model="year" 
            bar-height="5px"
            :max="yearRange[1]"
            :min="yearRange[0]"
          >
            <div class="buttonWrap" slot="button">
              <div class="sliderText">
                {{ year }}年
              </div>
              <div class="button"></div>
            </div>
          </van-slider>
        </van-cell>
        <van-field
          v-model.trim="workPlace"
          required
          clearable
          label="工作单位"
          placeholder="请输入"
        />
        <van-cell class="form" title="收入证明材料（点击上传）">
          <info-uploader 
            resultValue="incomeValue"
            @upload-read="uploadRead"
            @upload-delete="uploadDelete"
          >
          </info-uploader>
        </van-cell>
        <van-cell class="form" title="抵押物  （点击上传）">
           <info-uploader 
            resultValue="pledgeValue"
            @upload-read="uploadRead"
            @upload-delete="uploadDelete"
          >
          </info-uploader>
        </van-cell>
        <info-picker
          resultValue="area"
          label="办理网点区域"
          :value="areaString != '' ? areaString : ''"
          placeholder="请选择就近网点区域"
          :columns="areas"
          @picker-confirm="areaConfirm"
          @picker-change="areaChange"
          hasBeforeClick
          ref="areaPicker"
        >
        <!-- @before-click="displayArea" 控件要选择的话，尽管加上这个选项就好 -->
        </info-picker>
        <info-picker
          resultValue="branch"
          label="办理地点"
          :value="branch != '' ? branch.name : ''"
          placeholder="请选择就近网点办理"
          :columns="branches"
          @picker-confirm="branchConfirm"
          hasBeforeClick
          @before-click="displayBranches"
          ref="branchPicker"
        >
        </info-picker>
        <info-picker
          resultValue="manager"
          label="客户经理"
          :value="manager != '' ? manager.name : ''"
          placeholder="请选择客户经理"
          :columns="managers"
          @picker-confirm="pickerConfirm"
          hasBeforeClick
          @before-click="displayManagers"
          ref="managerPicker"
        >
        </info-picker>
      </van-cell-group>
    </van-panel>
    <section class="van-section">
      <section class="van-block">
        <h2 class="van-title switch" style="line-height:27px">
          <van-switch v-model="moreInfo" size="25px" />
           提供更多信息，使业务办理更加快捷
        </h2>
      </section>
    </section>
    <van-panel title="扩展信息" v-if="moreInfo">
      <van-cell-group>
        <van-field
          v-if="marriage == 1"
          v-model.trim="mateName"
          clearable
          label="配偶姓名"
          placeholder="请输入"
        />
        <info-picker
          v-if="marriage == 1"
          resultValue="mateCertificateType"
          label="配偶证件类型"
          :value="mateCertificateType != '' ? mateCertificateType.name : ''"
          placeholder="选择证件类型"
          :columns="mateCertificateTypes"
          @picker-confirm="pickerConfirm"
        >
        </info-picker>
        <van-field
          v-if="marriage == 1"
          v-model.trim="mateCertificateNum"
          clearable
          label="配偶证件号码"
          placeholder="请输入"
        />
        <van-cell 
          v-if="marriage == 1"
          class="form" 
          title="配偶证件复印件（点击上传）"
        >
          <info-uploader 
            resultValue="mateCertificateValue"
            @upload-read="uploadRead"
            @upload-delete="uploadDelete"
          >
          </info-uploader>
        </van-cell>
        <van-cell 
          v-if="marriage == 1"
          class="form" 
          title="婚姻证明文件（点击上传）"
        >
          <info-uploader 
            resultValue="marriageCertificateValue"
            @upload-read="uploadRead"
            @upload-delete="uploadDelete"
          >
          </info-uploader>
        </van-cell>
        <info-picker
          resultValue="giveWay"
          label="发放方式"
          :value="giveWay != '' ? giveWay.name : ''"
          placeholder="选择发放方式"
          :columns="giveWays"
          @picker-confirm="pickerConfirm"
        >
        </info-picker>
        <van-cell class="form" title="住房公积金对账薄姓名页复印件（点击上传）">
          <info-uploader 
            resultValue="housingFundNameValue"
            @upload-read="uploadRead"
            @upload-delete="uploadDelete"
          >
          </info-uploader>
        </van-cell>
        <van-cell class="form" title="住房公积金对账薄近半年流水页复印件（点击上传）">
          <info-uploader 
            resultValue="housingFundStatementValue"
            @upload-read="uploadRead"
            @upload-delete="uploadDelete"
          >
          </info-uploader>
        </van-cell>
      </van-cell-group>
    </van-panel>
    <br v-if="moreInfo"/>
    <van-panel title="验证手机号">
      <van-cell-group>
        <phone-and-code ref="fields"></phone-and-code>
      </van-cell-group>
    </van-panel>
    <br/>
    <br/>
    <br/>
    <br/>
    <div class="bottom">
      <van-button 
        size="large" 
        :loading="appLoading"
        loading-text="加载中"
        color="linear-gradient(to right, #4bb0ff, #6149f6)"
        @click="submit"
      >
        提交申请
      </van-button>
    </div>
  </div>
</template>

<script>
  import { NavBar, Panel, Icon, CellGroup, Cell, Field, RadioGroup, Radio, Slider, Switch, Button } from 'vant';
  import { default as PhoneAndCode } from '../../components/PhoneAndCode';
  import { default as InfoUploader } from '../../components/InfoUploader';
  import { default as InfoPicker } from '../../components/InfoPicker';
  import { mixins } from '../../common/mixins';
  import { mapState, mapMutations } from 'vuex';
  const ChineseDistricts = require('../../common/city-picker.data.min');

  export default {
    name: 'apply',
    components: {
      [NavBar.name]: NavBar,
      [Panel.name]: Panel,
      [CellGroup.name]: CellGroup,
      [Cell.name]: Cell,
      [Field.name]: Field,
      [Icon.name]: Icon,
      [RadioGroup.name]: RadioGroup,
      [Radio.name]: Radio,
      [Slider.name]: Slider,
      [Switch.name]: Switch,
      [Button.name]: Button,
      PhoneAndCode,
      InfoUploader,
      InfoPicker
    },
    mixins: [mixins],
    data () {
      return {
        displayLoanProj: false,
        loanProj: '',
        loanList: [],
        id: '',
        loanName: '',
        applicant: '',
        gender: '1', // 0-女 1-男
        certificateType: '',
        certificateTypes: [],
        certificateNum: '',
        marriage: '0', // 0-未婚 1-已婚 2-离异
        priceRange: [],
        price: 1,
        yearRange: [],
        year: 1, 
        workPlace: '',
        incomeValue: [],
        pledgeValue: [],
        defaultArea: '440281', // 初始化或列改变时候默认选中区域值
        area: [],
        areas: [],
        bankId: '',
        branch: '',
        branches: [],
        managerId: '',
        manager: '',
        managers: [],
        moreInfo: false,
        mateName: '',
        mateCertificateType: '',
        mateCertificateTypes: [],
        mateCertificateNum: '',
        mateCertificateValue: [],
        marriageCertificateValue: [],
        giveWay: '',
        giveWays: [],
        housingFundNameValue: [],
        housingFundStatementValue: [],
        rate: 0
      }
    },
    computed: {
      ...mapState ([
        'appLoading' // 将 this.appLoading 映射为 this.$store.state.appLoading
      ]),
			...mapState ('info', [ // 带命名空间的方法
        'saleInfo'
      ]),
      areaString () {
        let result = '';
        if(typeof(this.area) == 'string') result = this.area;
        else if(this.area instanceof Array && this.area.length > 0)
          result = 
            this.area[0].name + '/' + this.area[1].name + '/' + this.area[2].name;
        return result;
      }
    },
    created () {
      this.id = this.$route.query.id || '';
      this.loanName = this.$route.query.name || '[选择项目]';
      this.area = this.saleInfo.province || [{"name":"广东省","id":"440000"},{"name":"韶关市","id":"440200"},{"name":"乐昌市","id":"440281"}];
      this.bankId = this.saleInfo.bankId || '';
      this.managerId = this.saleInfo.managerId || '';
      this.displayLoanProj = this.id == '' ? true : false;
      Promise.all([this.initBranches(), this.initDetailChoose(), this.initLoanList()]).then( (res)=> {
        //console.log(res);
        if(typeof(this.area) == 'string' && this.area != ''){
          this.branches.forEach( (item) => {
            if(item.id == this.bankId) 
              this.branch = item;
          });
          this.initManagers().then(() => {
            if(this.managerId != '')
              this.managers.forEach( (item) => {
                if(item.userId == this.managerId) 
                  this.manager = item;
              });
          }); 
        }
        this.certificateTypes = res[1].data[0];
        this.mateCertificateTypes = res[1].data[0];
        this.giveWays = res[1].data[1];
        this.loanList = res[2].data;
        if(this.id != '') this.initPriceAndYear();
      });
      /* this.initBranches().then(() => {
        if(typeof(this.area) == 'string' && this.area != ''){
          this.branches.forEach( (item) => {
            if(item.id == this.bankId) 
              this.branch = item;
          });
          this.initManagers().then(() => {
            if(this.managerId != '')
              this.managers.forEach( (item) => {
                if(item.userId == this.managerId) 
                  this.manager = item;
              });
          }); 
        }
      });  */
      /* this.$api.info.getDetailChoose( (res) => {
        this.certificateTypes = res.data[0];
        this.mateCertificateTypes = res.data[0];
        this.giveWays = res.data[1];
        this.$api.info.getLoanList( (res) => {
          this.loanList = res.data;
          if(this.id != '') this.initPriceAndYear();
        });
      }); */
    },
    watch: {
      defaultArea () {
        this.initDistricts();
      }
    },
    methods: {
      initDetailChoose() {
        return new Promise( (resolve) => {
          this.$api.info.getDetailChoose( (res) => {
            resolve(res);
          });
        })
      },
      initLoanList() {
        return new Promise( (resolve) => {
          this.$api.info.getLoanList( (res) => {
            resolve(res);
          });
        })
      },
      ...mapMutations ('info', [ // 带命名空间的方法
        'clearSaleInfo'
      ]),
      loanProjConfirm (obj) {
        this.pickerConfirm(obj);
        this.id = obj.selectedObj.id;
        this.loanName = obj.selectedObj.name;
        this.initPriceAndYear();
      },
      initPriceAndYear () {
        this.loanList.forEach( (item) => {
          if(item.id == this.id){
            this.priceRange = [1, item.price];
            this.price = this.priceRange[0];
            this.yearRange = [1, item.year];
            this.year = this.yearRange[0];
            this.rate = item.rate;
          }
        });
      },
      displayArea () {
        if(typeof(this.area) == 'string' && this.area != ''){
          this.$UIplugins.message({
            message: '该项被设定为不能选择', 
            type: 'error'
          });
        }else{
          this.initDistricts();
          this.$refs.areaPicker.openPopup();
        }
      },
      initDistricts () {
        let proviceNumber = this.defaultArea.slice(0,2) + '0000',
            proviceList = ChineseDistricts[86], 
            proviceList_i = [], 
            i = 0, 
            proviceIndex = 0;
        for(var key in proviceList){
          proviceList[key].forEach(item => {
            if(proviceNumber == item.code) proviceIndex = i;
            proviceList_i.push({
              name:item.address,
              id:item.code
            });
            i++;
          });
        }
        let cityNumber = this.defaultArea.slice(0,4) + '00',
            cityList = ChineseDistricts[proviceNumber], 
            cityList_i = [], 
            j = 0, 
            cityIndex = 0;
        for(var key in cityList){
          if(key == cityNumber) cityIndex = j;
          cityList_i.push({
            name:cityList[key],
            id:key
          });
          j++;
        }
        let districtNumber = this.defaultArea,
            districtList = ChineseDistricts[cityNumber], 
            districtList_i = [], 
            k = 0, 
            districtIndex = 0;
        for(var key in districtList){
          if(key == districtNumber) districtIndex = k;
          districtList_i.push({
            name:districtList[key],
            id:key
          });
          k++;
        }
        this.areas = [
          {values: proviceList_i, defaultIndex: proviceIndex},
          {values: cityList_i, defaultIndex: cityIndex},
          {values: districtList_i, defaultIndex: districtIndex},
        ];
        //console.log(this.areas);
      },
      areaChange (obj) {
        let { picker, values, index } = obj;
        //console.log(picker, values, index);
        if(index == 0){
          let proviceNumber = values[0].id;
          let cityList = ChineseDistricts[proviceNumber];
          let cityNumber = Object.keys(cityList)[0];
          let districtList = ChineseDistricts[cityNumber];
          this.defaultArea = Object.keys(districtList)[0];
        }else if( index == 1){
          let cityNumber = values[1].id;
          let districtList = ChineseDistricts[cityNumber];
          this.defaultArea = Object.keys(districtList)[0];
        }
      },
      areaConfirm (obj) {
        this.pickerConfirm(obj);
        this.initBranches();
      },
      displayBranches () {
        if(typeof(this.area) == 'string' && this.area != '' && this.bankId != ''){
          this.$UIplugins.message({
            message: '该项被设定为不能选择', 
            type: 'error'
          });
        }else{
          if(this.area.length > 0) this.$refs.branchPicker.openPopup();
          else this.$UIplugins.message({
              message: '请先选择网点区域', 
              type: 'error'
            });
        }
      },
      initBranches () {
        return new Promise ( (resolve) => {
          this.branch = '';
          if(this.areaString != '')
            this.$api.info.getBranches( this.areaString, (res) => {
              this.branches = res.data;
              resolve();
            });
        });
      },
      branchConfirm (obj) {
        this.pickerConfirm(obj);
        console.log(this.branch)
        this.initManagers();
      },
      displayManagers () {
        if(typeof(this.area) == 'string' && this.area != '' && this.bankId != '' && this.managerId != ''){
          this.$UIplugins.message({
            message: '该项被设定为不能选择', 
            type: 'error'
          });
        }else{
          if(this.branch != '') this.$refs.managerPicker.openPopup();
          else this.$UIplugins.message({
              message: '请先选择办理地点', 
              type: 'error'
            });
        }
      },
      initManagers (callback) {
        return new Promise ( (resolve) => {
          this.manager = '';
          if(this.branch != '')
            this.$api.info.getManagers( this.branch.id, (res) => {
              this.managers = res.data;
              resolve();
            });
        });
      },
      pickerConfirm (obj) {
        this[obj.resultValue] = obj.selectedObj;
      },
      uploadRead(obj) {
        this[obj.resultValue] = this[obj.resultValue].concat(obj.pathArray);
      },
      uploadDelete(obj) {
        this[obj.resultValue].splice(obj.index, 1); 
      },
      submit () {
        let flag = 0, errorItem = '';
        if(this.branch == '') {flag++; errorItem = '办理地点';}
        /* if(this.pledgeValue.length <= 0) {flag++; errorItem = '抵押物';}
        if(this.incomeValue.length <= 0) {flag++; errorItem = '收入证明材料';} */
        if(this.workPlace == '') {flag++; errorItem = '工作单位';}
        if(this.certificateNum == '') {flag++; errorItem = '证件号码';}
        if(this.certificateType == '') {flag++; errorItem = '证件类型';}
        if(this.applicant == '') {flag++; errorItem = '申请人';}
        if(this.id == '') {flag++; errorItem = '贷款项目';}
        if(flag == 0){
          let checkResult = this.$refs.fields.checkSubmit();
          if (checkResult.result){
            let reqParams = {
              id: this.id,
              applicant: this.applicant,
              gender: this.gender,
              certificateTypeId: this.certificateType.id,
              certificateNum: this.certificateNum,
              marriage: this.marriage, 
              price: this.price,
              year: this.year, 
              workPlace: this.workPlace,
              incomeValue: this.incomeValue,
              pledgeValue: this.pledgeValue,
              area: this.areaString,
              branchId: this.branch.id,
              managerId: this.manager.userId,
              mateName: this.mateName,
              mateCertificateTypeId: this.mateCertificateType.id,
              mateCertificateNum: this.mateCertificateNum,
              mateCertificateValue: this.mateCertificateValue,
              marriageCertificateValue: this.marriageCertificateValue,
              giveWayId: this.giveWay.id,
              housingFundNameValue: this.housingFundNameValue,
              housingFundStatementValue: this.housingFundStatementValue,
              phone: checkResult.reqParams.phone,
              smsCode: checkResult.reqParams.smsCode,
              rate: this.rate
            };
            this.$api.info.submitApply(reqParams, (res) => {
              this.clearSaleInfo();
              this.$UIplugins.message({
                message: errorItem + '申请成功，即将跳转',
                type: 'loading',
                forbidClick: true,
                closeCallback: () => {
                  this.$router.push({path: '/process'});
                }
              });
            });
          }
        }else{
          this.$UIplugins.message({
            message: errorItem + '必须填写或选择', 
            type: 'error'
          });
        }
      }
    }
  }
</script>

<style lang="scss">
  .apply {
    .form{
      .van-cell__title, .van-cell__value{
        -webkit-box-flex: 8;
        -webkit-flex: 8;
        flex: 8;
      }
      .van-cell__title{
        -webkit-box-flex: 3;
        -webkit-flex: 3;
        flex: 3;
      }
      .van-cell__value{
        text-align: left;
        .van-radio-group{
          display: flex;
          .van-radio{margin-right: 10px;}
        }
        .van-slider{
          margin: 40px 28px 13px;
          .buttonWrap{
            margin-top: -30px;
            .sliderText{
              background-color: #1989fa;
              color: #fff;
              padding: 0 2px;
              border-radius: 5px;
              min-width: 40px;
              text-align: center;
              margin: 0 0 3px -10px;
            }
            .button{
              width: 24px;
              height: 24px;
              background-color: #fff;
              border-radius: 50%;
              box-shadow: 0 1px 2px rgba(38, 38, 38, 0.8);
            }
          }
        }
        .van-uploader{
          margin: 10px 0 0;
        }
      }
    }
    .bottom{
      width: 100%;
      position: fixed;
      bottom: 0;
      left: 0;
      z-index: 100;
    }
  }
</style>
